package com.fancy.learncenter.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.activity.base.MallCommonH5Activity;
import com.fancy.learncenter.ui.view.zxing.camera.CameraManager;
import com.fancy.learncenter.ui.view.zxing.decoding.CaptureActivityHandler;
import com.fancy.learncenter.ui.view.zxing.decoding.InactivityTimer;
import com.fancy.learncenter.ui.view.zxing.view.DialogAddBaby;
import com.fancy.learncenter.ui.view.zxing.view.ViewfinderView;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.PermissionHelper;
import com.fancy.learncenter.utils.StrUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.ta.utdid2.android.utils.StringUtils;

import java.io.IOException;
import java.util.Vector;

public class ScanActivity extends BaseActivity implements SurfaceHolder.Callback {
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private DialogAddBaby dialog;
    ImageView imageBack;
    TextView title;



    PermissionHelper mHelper;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan, Status.STATUS);
        imageBack = (ImageView) findViewById(R.id.back_image);
        title = (TextView) findViewById(R.id.title);
        title.setText("扫描二维码");
        imageBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);

        mHelper = new PermissionHelper(this);
//
        mHelper.requestPermissions("请授予非凡学习文件获取权限！",
                new PermissionHelper.PermissionListener() {
                    @Override
                    public void doAfterGrand(String... permission) {
                        LogUtil.MyLog("mHelper", "========确认=======");
                    }

                    @Override
                    public void doAfterDenied(final String... permission) {
                        LogUtil.MyLog("mHelper", "========拒绝=======" + permission.toString());
                        mHelper.showMessageOKCancel(getResources().getString(R.string.recode_permission), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mHelper.executePermissionsRequest(ScanActivity.this, new String[]{Manifest.permission.CAMERA}, mHelper.REQUEST_PERMISSION_CODE);
                            }
                        });
                    }
                }, new String[]{Manifest.permission.CAMERA});
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }


    public void handleDecode(Result result) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if (StrUtil.isFormatInteger(resultString)) {
            Intent intent = new Intent(this, MallCommonH5Activity.class);
            intent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getISBNBook(resultString));
            startActivity(intent);
            finish();
        } else if (resultString.contains("http")) {
            Intent intent = new Intent(this, MallCommonH5Activity.class);
            intent.putExtra(MallCommonH5Activity.URL_KEY, resultString);
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(this, ScanResultActivity.class);
            intent.putExtra("scan_result", resultString);
            startActivity(intent);
            finish();
        }


//        initData();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            showDialog();
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    private void showDialog() {
//        if (dialog == null) {
//            dialog = new DialogAddBaby(this, "提示", "无法获取摄像头数据，请检查是否已经打开摄像头权限。");
//            dialog.setCanceledOnTouchOutside(false);
//            dialog.show();
//        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
